﻿using System;
using System.Xml.Linq;

using SBPweb.Communication.Shared.Library.Contacts;
using SBPweb.Communication.Shared.Library.Conversations;

using SBPweb.Communication.Client.Library.Xmpp.Contacts;

namespace SBPweb.Communication.Client.Library.Xmpp.Conversations
{

    partial class Message : MessageBase
    {

        #region Internal fields

        internal Matrix.Xmpp.Client.Message message;

        #endregion

        #region Constructor logic

        internal Message(Matrix.Xmpp.Client.Message message)
            : base()
        {
            this.message = message;
            if (message.From != null)
            {
                this.from = new Contact(message.From);
            }
            if (message.To != null)
            {
                this.to = new Contact(message.To);
            }

            if (message.XDelay != null)
            {
                XAttribute xA = message.XDelay.Attribute("stamp");
                if (xA != null && xA.Value != null)
                {
                    TimeStamp = DateTime.Parse(xA.Value.Replace("T", ". ").Insert(4, ".").Insert(7, "."));
                }
            }
        }

        public Message(string body)
            : this(new Matrix.Xmpp.Client.Message())
        {
            Body = body;
        }

        #endregion

        #region Property accessors

        public override IContact From
        {
            get
            {
                return from;
            }
            set
            {
                from = value as Contact;
                if (message != null)
                {
                    message.From = new Matrix.Jid(value.Id);
                }
            }
        }

        public override IContact To
        {
            get
            {
                return to;
            }
            set
            {
                to = value as Contact;
                if (message != null)
                {
                    message.To = new Matrix.Jid(value.Id);
                }
            }
        }

        #endregion

    }

}